from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from app.core.request_context import generate_request_id, set_request_id, get_request_id
import logging

logger = logging.getLogger(__name__)


class RequestIDMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next) -> Response:
        # 1. 生成新的 request_id
        request_id = generate_request_id()

        # 2. 存入上下文，供后续链路使用
        set_request_id(request_id)

        # 调试：立即验证是否设置成功
        current_request_id = get_request_id()
        print(f"🔍 [中间件调试] 设置 request_id: {request_id}, 当前获取: {current_request_id}")

        # 3. 记录请求开始日志（包含 request_id）
        logger.info(f"开始处理请求 {request_id}: {request.method} {request.url}")

        try:
            # 处理请求
            response = await call_next(request)

            # 4. 在响应头中返回 request_id（方便前端/客户端追踪）
            response.headers["X-Request-ID"] = request_id

            # 调试：处理完成后再次验证
            final_request_id = get_request_id()
            print(f"🔍 [中间件调试] 请求完成，最终 request_id: {final_request_id}")

            return response
        except Exception as e:
            logger.error(f"请求 {request_id} 处理失败: {str(e)}")
            raise
        finally:
            # 记录请求结束日志（包含 request_id）
            logger.info(f"请求 {request_id} 处理完成")